<?php
/**
 * 正道项目 - 商品接口类
 * @author   yubo <yubo@ebsig.com>
 * @version 1.0
 */

namespace App\Service\Rpc\Goods;
use Carbon\Carbon;
use App\Models\Goods\GoodsImport;  //导入商品表
use GuzzleHttp\Client;
use App\Models\Goods\LogEaiGoods; //商品基础资料表

class ZdGoods
{

    /**
     * 查询线下商品资料
     * @return array
     */
    public function query()
    {
        $page = 1;

        $url = 'www.weeass.cc/getGoodsList'; //接口地址

        while ($page > 0) {

            $param = [
                'curPage' => $page,
                'pageSize' => 100
            ];

            $goods_data =  $this->requestApi($url,'getGoodsList', array(), json_encode($param),'post');
            if( $goods_data['code'] != 200 || empty($goods_data['data']) ){
                die();
            }

            ++$page;

            $goods_conten = [];
            foreach ($goods_data as &$goods) {
                $goods_conten[] = [
                    'mainPostID' => 0,
                    'goods_type' => 1,
                    'goodsName' => $goods['Name'],
                    'brandID' => 0,
                    'unitID' => 0,
                    'brief' => '',
                    'pc_description' => '',
                    'mobile_description' => '',
                    'bigCategoryID' => 0,
                    'midCategoryID' => 0,
                    'smallCategoryID' => 0,
                    'goods_limit' => 0,
                    'forsale_type' => 0,
                    'supplier_id' => 1,
                    'spec_type' => 0,
                    'WAP' => 1,
                    'PC' => 1,
                    'APP' => 1,
                    'goods' => [
                        0 => [
                            'product_code' => $goods['BarcodeID'],
                            'spec1' => '',
                            'spec2' => '',
                            'sale_price' => '1.00',
                            'market_price' => '1.00',
                            'cost_price' => '0.00',
                            'higher_price' => '',
                            'lower_price' => '0.00',
                            'product_rate' => '',
                            'record_price' => '',
                            'record_code' => '',
                            'customs_product_code' => '',
                            'weight' => 0,
                            'sale_points' => '0',
                            'product_spec' => 1
                        ]
                    ]

                ];

            }

            /**
             * =======保存数据=========
             */

            $product_import = GoodsImport::store( $goods_conten );
                if ($product_import['code'] != 200) {
                    continue;
                }

            /**
             * =======保存数据=========
             */

        }

        return ['code' => 200, 'message' => 'ok'];

    }

    public function requestApi($request_url, $api_name, $get_data = [], $post_data = [], $request_way = 'get' )
    {

        //http实例化
        $client = new Client();

        //接口参数
        $data = $this->createSign($post_data);

        $post_data[] = [
            'data' => $data
        ];

        /*
         * ==========接口请求==============
         */
        $res = $client->post($request_url , ['body' => $post_data]);
        $result_array = json_decode($res->getBody(), true);

        $return_data = [];
        if ($result_array['code'] == 200) {

            if ($result_array['data']['code'] == 0) {
                $result_data['code'] = 200;
                $return_data = json_decode($this->decrypt($result_array['data']['data']),true);
            } else {
                $result_data['code'] = 400;
            }

        } else {
            return ['message' => '接口出错：操作失败', 'code' => 500];
        }


        /**
         * =======商品接口日志==========
         */
        $log_interface = new LogEaiGoods();
        $log_interface->creator = 'fuji';
        $log_interface->bill_no = '';
        $log_interface->product_code = '';
        $log_interface->mallCode = '';
        $log_interface->api_name = $api_name;
        if( !empty($get_data) && !empty($post_data) ){
            $log_interface->request_data = print_r(array_merge($get_data, $post_data), true);
        } else if ( !empty($get_data) ){
            $log_interface->request_data = print_r($get_data, true);
        } else if ( !empty($post_data) ){
            $log_interface->request_data = print_r($post_data, true);
        }
        $log_interface->return_data = print_r($result_data, true);
        $log_interface->return_code = $result_data['code'];
        $log_interface->return_msg  = $result_array['data']['message'];
        $log_interface->exec_time =Carbon::now();
        $log_interface->save();

        /**
         * =======商品接口日志==========
         */

        return $return_data;
    }

    //获取加密签名
    private function createSign($data){

        $cipher = MCRYPT_RIJNDAEL_128;        //加密类型
        $mode = MCRYPT_MODE_ECB;            //加密模式

        $blocksize = mcrypt_get_block_size ( $cipher, $mode );
        $pad = $blocksize - (strlen ( $data ) % $blocksize);
        $str = $data . str_repeat ( chr ( $pad ), $pad );

        $str_encrypt = mcrypt_encrypt($cipher, $this->key, $str, $mode);

        return base64_encode($str_encrypt);

    }

    //解密返回信息
    private function decrypt( $data ){

        $cipher = MCRYPT_RIJNDAEL_128;    //加密类型
        $mode = MCRYPT_MODE_ECB;        //加密模式

        $str = base64_decode($data);

        $str_decrypt = mcrypt_decrypt($cipher, $this->key, $str, $mode);

        $pad = ord($str_decrypt {strlen($str_decrypt) - 1});
        if ($pad > strlen($str_decrypt))
            return false;
        if (strspn($str_decrypt, chr($pad), strlen($str_decrypt) - $pad) != $pad)
            return false;
        $str_decrypt = substr($str_decrypt, 0, - 1 * $pad);

        return $str_decrypt;

    }
}